<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 各供应商应用的公共设置库存或价格
 */
class Controller_Price extends Stourweb_Controller
{
    public $admin_id;
    public function before()
    {
        $session = Session::instance();
        $this->admin_id = $session->get('userid');
    }

    /**
     * 公告设置库存页
     */
    public function action_dialog_edit_all_suit_number()
    {
        $suit_id = Common::remove_xss(Arr::get($_GET, 'suit_id'));
        $type_id = Common::remove_xss(Arr::get($_GET, 'type_id'));

        $this->assign('suit_id',$suit_id);
        $this->assign('type_id',$type_id);
        $this->display('stourtravel/dialog/set_number');
    }

    /**
     * 设置总库存，公共方法
     */
    public function action_ajax_save_all_number()
    {
        $params = array(
            'start_time'  => Common::remove_xss(Arr::get($_POST, 'start_time')),
            'end_time'    => Common::remove_xss(Arr::get($_POST, 'end_time')),

            'number_type' => Common::remove_xss(Arr::get($_POST, 'number_type')),
            'number'      => Common::remove_xss(Arr::get($_POST, 'number')),

            'number_rule' => Common::remove_xss(Arr::get($_POST, 'number_rule')),
            'week_val'    => Common::remove_xss(Arr::get($_POST, 'week_val')),
            'month_val'   => Common::remove_xss(Arr::get($_POST, 'month_val')),

            'suit_id'     => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'     => Common::remove_xss(Arr::get($_POST, 'type_id')),
        );
        if(!$params['suit_id'] && !$params['type_id']){
            exit(json_encode(array('status'=>false,'msg'=>'参数缺失，请刷新重试')));
        }
        if(!$params['start_time'] || !$params['end_time']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围')));
        }
        if($params['number_rule']==2 && !$params['week_val']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围下的星期')));
        }
        if($params['number_rule']==3 && !$params['month_val']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围下的天')));
        }
        if($params['number_type']==1){
            $params['number'] = '-1';
        }else{
            $params['number'] = $params['number']?$params['number']:0;
        }

        $status = Model_Price_Number::set_product_number($params);
        if($status['status']){
            $params['describe'] = '批量设置库存';
            Model_Price_Record::add_record($params,null,$this->admin_id);
        }
        echo json_encode($status);
    }

    /**
     * 公告设置单天库存页面
     */
    public function action_dialog_edit_single_suit_number()
    {
        $suit_id = Common::remove_xss(Arr::get($_GET, 'suit_id'));
        $date = Common::remove_xss(Arr::get($_GET, 'date'));
        $type_id = Common::remove_xss(Arr::get($_GET, 'type_id'));

        $table = St_Functions::table_field($type_id);
        $day = strtotime($date);
        $number = DB::select()->from($table[4])->where("suit_id={$suit_id} and day={$day}")->execute()->get('number');

        $this->assign('number',$number=='不限'?'-1':$number);
        $this->assign('suit_id',$suit_id);
        $this->assign('type_id',$type_id);
        $this->assign('date',$date);
        $this->display('stourtravel/dialog/set_number');
    }

    /**
     * 公共设置单天库存
     */
    public function action_ajax_save_single_number()
    {
        $params = array(
            'date'    => Common::remove_xss(Arr::get($_POST, 'date')),

            'number_type' => Common::remove_xss(Arr::get($_POST, 'number_type')),
            'number'      => Common::remove_xss(Arr::get($_POST, 'number')),

            'suit_id'     => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'     => Common::remove_xss(Arr::get($_POST, 'type_id')),
        );
        if(!$params['suit_id'] && !$params['type_id']){
            exit(json_encode(array('status'=>false,'msg'=>'参数缺失，请刷新重试')));
        }
        if($params['number_type']==1){
            $params['number'] = '-1';
        }
        $status = Model_Price_Number::set_product_single_number($params);
        if($status['status']){
            $params['describe'] = '设置单日库存';
            Model_Price_Record::add_record($params,null,$this->admin_id);
        }
        echo json_encode($status);
    }

    /**
     * 公共获取日历库存
     */
    public function action_ajax_get_calendar_number()
    {
        $suit_id = Common::remove_xss(Arr::get($_POST, 'suit_id'));
        $type_id = Common::remove_xss(Arr::get($_POST, 'type_id'));
        $year = Common::remove_xss(Arr::get($_POST, 'y'));
        $month = Common::remove_xss(Arr::get($_POST, 'm'));

        $table_field = St_Functions::table_field($type_id);
        $day = strtotime(date('Ymd'));
        $calendar = DB::select()->from($table_field[4])->where("suit_id={$suit_id} and day>={$day}")->order_by('day','ASC')->execute()->current();

        $allowed_days = array();
        $list = array();
        $starttime = $year && $month?$year.'-'.$month.'-1':date('Y-m-d',$calendar['day']);
        $last_date = date('Y-m-t',strtotime($starttime));

        $start_date = strtotime($starttime);
        $end_date = strtotime($last_date);
        $calendar_number = DB::select()->from($table_field[4])->where("suit_id={$suit_id} and day>={$start_date} and day<={$end_date}")->execute()->as_array();
        foreach ($calendar_number as $v){
            $date = date('Y-m-d',$v['day']);
            array_push($allowed_days,$date);
            $data = array(
                'number'        => $v['number']=='-1'?'不限':$v['number'],
                $table_field[1] => $v['product_id'],
                $table_field[5] => $v['suit_id'],
                'date'          => date('Y-m-d',$v['day'])
            );
            array_push($list,$data);
        }

        $params = array(
            'allowed_days' => $allowed_days,
            'list'         => $list,
            'starttime'    => $starttime,
        );
        echo json_encode(array('status'=>true,'data'=>$params));
    }

    /**
     * 公共删除日历库存
     */
    public function action_ajax_clear_number()
    {
        $suit_id = Common::remove_xss(Arr::get($_POST, 'suit_id'));
        $type_id = Common::remove_xss(Arr::get($_POST, 'type_id'));

        $table_field = St_Functions::table_field($type_id);
        $res = DB::delete($table_field[4])->where('suit_id', '=', $suit_id)->execute();
        if($res){
            Model_Price_Record::add_record(array('suit_id'=>$suit_id,'type_id'=>$type_id,'describe'=>'平台删除了总库存，同时删除所有关联报价'),null,$this->admin_id);
        }
        /*清除库存直接同步清除所有报价*/
        $table_field = St_Functions::table_field($type_id);

        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        call_user_func_array(array($model, 'delete_price'), array('params'=>json_encode(array('suit_id'=>$suit_id,'channel_id'=>'1,2,3'))));

        $params = array(
            'status' => $res?true:false,
        );
        echo json_encode($params);
    }

    /**
     * 各应用公共报价弹窗
     */
    public function action_dialog_edit_all_suit_price()
    {
        $set_date = Common::remove_xss(Arr::get($_GET, 'date'));
        $suit_id = Common::remove_xss(Arr::get($_GET, 'suit_id'));
        $type_id = Common::remove_xss(Arr::get($_GET, 'type_id'));
        $channel_id = Common::remove_xss(Arr::get($_GET, 'channel_id'));
        $settlement_type = Common::remove_xss(Arr::get($_GET, 'settlement_type'));

        /*获取库存支持的时间范围*/
        $table_field = St_Functions::table_field($type_id);
        $date = strtotime(date('Ymd'));
        $min_day = DB::select(DB::expr('min(day) AS day'))->from($table_field[4])->where("day>={$date} and suit_id={$suit_id}")->execute()->get('day');
        $max_day = DB::select(DB::expr('max(day) AS day'))->from($table_field[4])->where("day>={$date} and suit_id={$suit_id}")->execute()->get('day');
        if($min_day && $max_day){
            $this->assign('min_day',date('Y-m-d',$min_day));
            $this->assign('max_day',date('Y-m-d',$max_day));
            $this->assign('status',true);
        }else{
            $this->assign('status',false);
        }
        $price = false;
        if($set_date){
            $setDate = strtotime($set_date);
            if($type_id>199){
                $price = DB::select()->from($table_field[6])->where("{$table_field[5]}={$suit_id} and day={$setDate}")->execute()->current();
            }else{
                $price = DB::select()->from($table_field[6])->where("{$table_field[5]}={$suit_id} and day={$setDate} and supplier_channel_id={$channel_id}")->execute()->current();
            }

            if($type_id==1){
                $price['propgroup'] = explode(',',$price['propgroup']);
            }
        }
        $people_group = self::people_group($type_id);
        /*获取结算类型及分佣比例*/
        $channel_id = $type_id>199?1:$channel_id;
        $settlement_config = DB::select()->from('supplier_settlement_config')
            ->where("type_id={$type_id} and suit_id={$suit_id} and channel_id={$channel_id}")
            ->execute()->current();
        $settlement_info = array(
            'settlement_type' => $settlement_type
        );
        if(!empty($settlement_config['settlement_val'])){
            $settlement_info['settlement_key'] = $settlement_config['settlement_key'];
            $settlement_info['settlement_val'] = $settlement_config['settlement_key']==1?bcmul($settlement_config['settlement_val'],100):$settlement_config['settlement_val'];
        }

        $this->assign('settlement_info',$settlement_info);
        $this->assign('price',$price);
        $this->assign('people_group',$people_group);
        $this->assign('set_date',$set_date);
        $this->assign('suit_id',$suit_id);
        $this->assign('type_id',$type_id);
        $this->assign('channel_id',$channel_id);
        $this->display('stourtravel/dialog/set_price');
    }

    public function people_group($type_id)
    {
        if($type_id==1){
            $people_group = Model_Sysconfig::get_people_group();
        }else if($type_id==114){
            $people_group = array(
                array(
                    'name'             => '成人',
                    'basicprice_field' => 'basicprice',
                    'profit_field'     => 'profit',
                    'price_field'      => 'price',
                ),
                array(
                    'name'             => '儿童',
                    'basicprice_field' => 'childbasicprice',
                    'profit_field'     => 'childprofit',
                    'price_field'      => 'childprice',
                ),
            );
        }elseif($type_id==2 || $type_id>199){
            $people_group = array(
                array(
                    'name'             => '价格',
                    'basicprice_field' => 'basicprice',
                    'profit_field'     => 'profit',
                    'price_field'      => 'price',
                )
            );
        }else{
            $people_group = array(
                array(
                    'name'             => '价格',
                    'basicprice_field' => 'adultbasicprice',
                    'profit_field'     => 'adultprofit',
                    'price_field'      => 'adultprice',
                )
            );
        }

        return $people_group;
    }

    /**
     * 公共产品报价
     */
    public function action_ajax_save_all_price()
    {
        $params = array(
            'start_time'         => Common::remove_xss(Arr::get($_POST, 'start_time')),
            'end_time'           => Common::remove_xss(Arr::get($_POST, 'end_time')),

            'price_rule'         => Common::remove_xss(Arr::get($_POST, 'price_rule')),
            'week_val'           => Common::remove_xss(Arr::get($_POST, 'week_val')),
            'month_val'          => Common::remove_xss(Arr::get($_POST, 'month_val')),

            'propgroup'          => Common::remove_xss(Arr::get($_POST, 'propgroup')),
            'room_balance'       => Common::remove_xss(Arr::get($_POST, 'room_balance')),
            'roombalance'        => Common::remove_xss(Arr::get($_POST, 'roombalance')),
            'suit_id'            => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'            => Common::remove_xss(Arr::get($_POST, 'type_id')),
            'channel_id'         => Common::remove_xss(Arr::get($_POST, 'channel_id')),

            'settlement_type'    => Common::remove_xss(Arr::get($_POST, 'settlement_type')),
            'settlement_key'     => Common::remove_xss(Arr::get($_POST, 'settlement_key')),
            'settlement_val'     => Common::remove_xss(Arr::get($_POST, 'settlement_val')),
        );
        $number_type = Common::remove_xss(Arr::get($_POST, 'number_type'));
        $params['number'] = $number_type==1?'-1':Common::remove_xss(Arr::get($_POST, 'number'));
        $price = array(
            'basicprice'         => Common::remove_xss(Arr::get($_POST, 'basicprice')),
            'profit'             => Common::remove_xss(Arr::get($_POST, 'profit')),
            
            'adultbasicprice'    => Common::remove_xss(Arr::get($_POST, 'adultbasicprice')),
            'adultprofit'        => Common::remove_xss(Arr::get($_POST, 'adultprofit')),
            'childbasicprice'    => Common::remove_xss(Arr::get($_POST, 'childbasicprice')),
            'childprofit'        => Common::remove_xss(Arr::get($_POST, 'childprofit')),
            'oldbasicprice'      => Common::remove_xss(Arr::get($_POST, 'oldbasicprice')),
            'oldprofit'          => Common::remove_xss(Arr::get($_POST, 'oldprofit')),
            'people4_basicprice' => Common::remove_xss(Arr::get($_POST, 'people4_basicprice')),
            'people4_profit'     => Common::remove_xss(Arr::get($_POST, 'people4_profit')),
            'people5_basicprice' => Common::remove_xss(Arr::get($_POST, 'people5_basicprice')),
            'people5_profit'     => Common::remove_xss(Arr::get($_POST, 'people5_profit')),
            'people6_basicprice' => Common::remove_xss(Arr::get($_POST, 'people6_basicprice')),
            'people6_profit'     => Common::remove_xss(Arr::get($_POST, 'people6_profit')),
        );
        foreach ($price as &$v){
            if($v===''){
                $v = 'null';
            }
        }
        $params = array_merge($params,$price);
        $total_price = array_sum($price);

//        if(!$total_price){
//            exit(json_encode(array('status'=>false,'msg'=>'请填写金额')));
//        }
        if($params['type_id']==1 && empty($params['propgroup'])){
            exit(json_encode(array('status'=>false,'msg'=>'请选择人群')));
        }
        if(!$params['suit_id'] || !$params['type_id']){
            exit(json_encode(array('status'=>false,'msg'=>'参数缺失，请刷新重试')));
        }
        if(!$params['start_time'] || !$params['end_time']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围')));
        }
        if($params['price_rule']==2 && !$params['week_val']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围下的星期')));
        }
        if($params['price_rule']==3 && !$params['month_val']){
            exit(json_encode(array('status'=>false,'msg'=>'请选择日期范围下的天')));
        }
        if(!$params['number'] && $params['number']!=='0'){
            exit(json_encode(array('status'=>false,'msg'=>'请填写限购数量')));
        }

        $table_field = St_Functions::table_field($params['type_id']);
        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        $res = call_user_func_array(array($model, 'set_calendar_quote'), array('params'=>json_encode($params)));
        if($res['status']){
            $params['describe'] = '批量报价';
            Model_Price_Record::add_record($params,null,$this->admin_id);
            /*按销售价结算时 修改套餐表中的报价*/
            if($params['settlement_type']==2){
                Model_Price_Settlement::suit_price_modify($params['type_id'],$params['suit_id'],$params['settlement_type']);
                Model_Price_Settlement::suit_modify($params);
            }
        }
        echo json_encode($res);
    }

    /**
     * 公共价格单天设置
     */
    public function action_ajax_save_single_price()
    {
        $params = array(
            'roombalance'        => Common::remove_xss(Arr::get($_POST, 'roombalance',0)),
            'propgroup'          => Common::remove_xss(Arr::get($_POST, 'propgroup')),
            'number'             => Common::remove_xss(Arr::get($_POST, 'number')),
            'number_type'             => Common::remove_xss(Arr::get($_POST, 'number_type')),//2数量 1:不限
            'suit_id'            => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'            => Common::remove_xss(Arr::get($_POST, 'type_id')),
            'channel_id'         => Common::remove_xss(Arr::get($_POST, 'channel_id')),
            'set_date'           => Common::remove_xss(Arr::get($_POST, 'set_date')),

            'settlement_type'    => Common::remove_xss(Arr::get($_POST, 'settlement_type')),
            'settlement_key'     => Common::remove_xss(Arr::get($_POST, 'settlement_key')),
            'settlement_val'     => Common::remove_xss(Arr::get($_POST, 'settlement_val')),
        );
        $price = array(
            'basicprice'         => Common::remove_xss(Arr::get($_POST, 'basicprice',0)),
            'profit'             => Common::remove_xss(Arr::get($_POST, 'profit',0)),
            'adultbasicprice'    => Common::remove_xss(Arr::get($_POST, 'adultbasicprice',0)),
            'adultprofit'        => Common::remove_xss(Arr::get($_POST, 'adultprofit',0)),
            'childbasicprice'    => Common::remove_xss(Arr::get($_POST, 'childbasicprice',0)),
            'childprofit'        => Common::remove_xss(Arr::get($_POST, 'childprofit',0)),
            'oldbasicprice'      => Common::remove_xss(Arr::get($_POST, 'oldbasicprice',0)),
            'oldprofit'          => Common::remove_xss(Arr::get($_POST, 'oldprofit',0)),
            'people4_basicprice' => Common::remove_xss(Arr::get($_POST, 'people4_basicprice',0)),
            'people4_profit'     => Common::remove_xss(Arr::get($_POST, 'people4_profit',0)),
            'people5_basicprice' => Common::remove_xss(Arr::get($_POST, 'people5_basicprice',0)),
            'people5_profit'     => Common::remove_xss(Arr::get($_POST, 'people5_profit',0)),
            'people6_basicprice' => Common::remove_xss(Arr::get($_POST, 'people6_basicprice',0)),
            'people6_profit'     => Common::remove_xss(Arr::get($_POST, 'people6_profit',0)),
        );
        foreach ($price as &$v){
            if($v===''){
                $v = null;
            }
        }
        $params = array_merge($params,$price);
        $total_price = array_sum($price);
        if(!$total_price){
            exit(json_encode(array('status'=>false,'msg'=>'请填写金额！')));
        }
        if($params['type_id']==1 && empty($params['propgroup'])){
            exit(json_encode(array('status'=>false,'msg'=>'请选择人群！')));
        }
        if($params['settlement_type']==2 && empty($params['settlement_key'])){
            exit(json_encode(array('status'=>false,'msg'=>'请填写结算信息！')));
        }

        $table_field = St_Functions::table_field($params['type_id']);
        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        $res = call_user_func_array(array($model, 'set_single_price'), array('params'=>json_encode($params)));
        if($res['status']){
            $params['describe'] = '单日报价';
            Model_Price_Record::add_record($params,null,$this->admin_id);
            /*按销售价结算时 修改套餐表中的报价*/
            if($params['settlement_type']==2){
                Model_Price_Settlement::suit_price_modify($params['type_id'],$params['suit_id'],$params['settlement_type']);
                Model_Price_Settlement::suit_modify($params);
            }
        }
        echo json_encode($res);
    }

    /**
     * 公共获取报价
     */
    public function action_ajax_get_suit_price()
    {
        $params = array(
            'year'       => Common::remove_xss(Arr::get($_POST, 'year')),
            'month'      => Common::remove_xss(Arr::get($_POST, 'month')),
            'suit_id'    => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'    => Common::remove_xss(Arr::get($_POST, 'type_id')),
            'channel_id' => Common::remove_xss(Arr::get($_POST, 'channel_id')),
        );

        $table_field = St_Functions::table_field($params['type_id']);
        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        $res = call_user_func_array(array($model, 'get_suit_price'), array('params'=>json_encode($params)));

        echo json_encode($res);
    }

    /**
     * 公共删除报价
     */
    public function action_ajax_delete_price()
    {
        $params = array(
            'suit_id'    => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'    => Common::remove_xss(Arr::get($_POST, 'type_id')),
            'channel_id' => Common::remove_xss(Arr::get($_POST, 'channel_id')),
            'product_id' => Common::remove_xss(Arr::get($_POST, 'product_id')),
        );

        $table_field = St_Functions::table_field($params['type_id']);
        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        $res = call_user_func_array(array($model, 'delete_price'), array('params'=>json_encode($params)));
        if($res['status']){
            $params['describe'] = '删除报价';
            Model_Price_Record::add_record($params,null,$this->admin_id);
        }
        echo json_encode($res);
    }

    public function action_ajax_rm_oneday_price(){
        $params = array(
            'suit_id'    => Common::remove_xss(Arr::get($_POST, 'suit_id')),
            'type_id'    => Common::remove_xss(Arr::get($_POST, 'type_id')),
            'channel_id' => Common::remove_xss(Arr::get($_POST, 'channel_id')),
            'product_id' => Common::remove_xss(Arr::get($_POST, 'product_id')),
            'set_date' => Common::remove_xss(Arr::get($_POST, 'set_date')),
        );

        $table_field = St_Functions::table_field($params['type_id']);
        $table = $table_field[3]=='model_archive'?'tongyong':$table_field[3];
        $model = 'Model_Price_'.ucfirst($table);
        $res = call_user_func_array(array($model, 'rm_oneday_price'), array('params'=>json_encode($params)));
        if($res['status']){
            $params['describe'] = '删除报价';
            Model_Price_Record::add_record($params,null,$this->admin_id);
        }
        echo json_encode($res);
    }
}